// src/server/request.js
import axios from 'axios';
import Message from '@/utils/message';
const instance = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器（可添加 token）
instance.interceptors.request.use(
  config => {
    const data = JSON.parse(localStorage.getItem('userinfo'));
    if (data && data.token) {
      config.headers['Authorization'] = `Bearer ${data.token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    if(response.data.code === 403){
      localStorage.removeItem('userinfo');
      Message.error(response.data.msg || '登录过期，请重新登录');
    }
    return response.data; // 直接返回 data，省去 .data
  },
  error => {
    console.error('请求失败:', error.response || error.message);
    return Promise.reject(error);
  }
);

export default instance;
